﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Assembly
{
    public partial class frm_Edit_F4Part : Form
    {
        private DataSet ds;
        private DataViewManager dsView;

        public string compid;

        public frm_Edit_F4Part()
        {
            InitializeComponent();
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.ds = new DataSet("Part");
            this.compid = null;

            this.partNo.LostFocus += partNo_LostFocus;
        }

        void partNo_LostFocus(object sender, EventArgs e)
        {
            if (this.partNo.FindString(this.partNo.Text.Trim()) > 0)
            {
                this.partNo.SelectedIndex = this.partNo.FindString(this.partNo.Text.Trim());
            }
        }

        //////////////////////////////////////////////
        /// Load Data
        /////////////////////////////////////////////
        public bool LoadData()
        {
            bool ret = true;
            if (string.IsNullOrEmpty(this.compid))
            {
                ret = false;
            }
            else
            {
                LoadPartList();
                try
                {
                    myConnection.Open();
                    SqlCommand sql_cmd = myConnection.CreateCommand();
                    sql_cmd.CommandText = "SELECT * FROM [231_Comp] WHERE CompID = '" + compid + "'";
                    SqlDataReader dataReader = sql_cmd.ExecuteReader();
                    if (dataReader.Read())
                    {
                        if (this.partNo.FindString(this.compid) > 0)
                        {
                            this.partNo.SelectedIndex = this.partNo.FindString(this.compid);
                        }
                        this.compName.Text = dataReader["CompName"].ToString().Trim();
                        this.productNo.Text = dataReader["Product"].ToString().Trim();
                        if (dataReader["AssemblyTime"] != DBNull.Value)
                        {
                            this.assTime.Text = dataReader["AssemblyTime"].ToString();
                        }
                        else
                        {
                            this.assTime.Text = "0";
                        }
                        if (dataReader["InspectorTime"] != DBNull.Value)
                        {
                            this.insTime.Text = dataReader["InspectorTime"].ToString();
                        }
                        else
                        {
                            this.insTime.Text = "0";
                        }
                        if (dataReader["WiringTime"] != DBNull.Value)
                        {
                            this.wTime.Text = dataReader["WiringTime"].ToString();
                        }
                        else
                        {
                            this.wTime.Text = "0";
                        }
                        if (dataReader["WCheckTime"] != DBNull.Value)
                        {
                            this.wcheckTime.Text = dataReader["WCheckTime"].ToString();
                        }
                        else
                        {
                            this.wcheckTime.Text = "0";
                        }
                        this.serialPrefix.Text = dataReader["Serial"].ToString().Trim();
                        this.compType.Text = dataReader["Type"].ToString().Trim();
                        this.compGroup.Text = dataReader["CompGroup"].ToString().Trim();
                        if (dataReader["NormalSerial"] != DBNull.Value)
                        {
                            if ((bool)dataReader["NormalSerial"])
                            {
                                this.normalSerial.Checked = true;
                            }
                        }

                        if (dataReader["MACSerial"] != DBNull.Value)
                        {
                            if ((bool)dataReader["MACSerial"])
                            {
                                this.macSerial.Checked = true;
                            }
                        }
                    }
                    sql_cmd.Dispose();
                }
                catch
                {
                    ret = false;
                }
                finally
                {
                    myConnection.Close();
                }
            }
            return ret;
        }
        
        /// <summary>
        /// Load Part List
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadPartList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT [PartNo], [PartEnglishName]"
                    + " FROM [222_Part]"
                    + " WHERE ([PartNo] NOT IN (SELECT CompID FROM [231_Comp])) OR (PartNo = '" + this.compid + "')";
                SqlDataAdapter da1 = new SqlDataAdapter();
                da1.SelectCommand = cmd_sql;
                da1.TableMappings.Add("Table", "Part");
                da1.Fill(ds);
                dsView = ds.DefaultViewManager;
                cmd_sql.Dispose();
                myConnection.Close();

                this.partNo.DataSource = dsView;
                this.partNo.DisplayMember = "Part.PartNo";
                this.partNo.ValueMember = "Part.PartNo";
                this.partNo.AutoCompleteSource = AutoCompleteSource.ListItems;

                this.partName.DataBindings.Add("Text", dsView, "Part.PartEnglishName");
            }
            catch (Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show(ex.Message);
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }        
        
        ///////////////////////////
        /// When Click Add Button
        ///////////////////////////        
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            string err = null;
            string partno = null;
            string partname = null;
            string compname = null;
            string product = null;
            int ass_time = 0;
            int ins_time = 0;
            int w_time = 0;
            int wcheck_time = 0;
            string serial_prefix = null;
            string comp_type = null;
            string comp_group = null;
            int normal_serial = 0;
            int mac_serial = 0;
            

            if (this.partNo.SelectedIndex < 0)
            {
                err = "Please select Part to add.";
            }
            else
            {
                partno = this.partNo.SelectedValue.ToString().Trim();
                partname = this.partName.Text.Trim();
            }

            if (string.IsNullOrEmpty(err))
            {
                if (!string.IsNullOrEmpty(this.assTime.Text.Trim()))                
                {
                    if (!Int32.TryParse(this.assTime.Text.Trim(), out ass_time))
                    {
                        err = "Invalid Assembly Time";
                    }                    
                }
            }

            if (string.IsNullOrEmpty(err))
            {
                if (!string.IsNullOrEmpty(this.insTime.Text.Trim()))
                {
                    if (!Int32.TryParse(this.insTime.Text.Trim(), out ins_time))
                    {
                        err = "Invalid Inspector Time";
                    }
                }
            }

            if (string.IsNullOrEmpty(err))
            {
                if (!string.IsNullOrEmpty(this.wTime.Text.Trim()))
                {
                    if (!Int32.TryParse(this.wTime.Text.Trim(), out w_time))
                    {
                        err = "Invalid Wiring Time";
                    }
                }
            }

            if (string.IsNullOrEmpty(err))
            {
                if (!string.IsNullOrEmpty(this.wcheckTime.Text.Trim()))
                {
                    if (!Int32.TryParse(this.wcheckTime.Text.Trim(), out wcheck_time))
                    {
                        err = "Invalid WCheck Time";
                    }
                }
            }

            if (string.IsNullOrEmpty(err))
            {
                compname = this.compName.Text.Trim();
                product = this.productNo.Text.Trim();
                serial_prefix = this.serialPrefix.Text.Trim();
                comp_type = this.compType.Text.Trim();
                if (this.normalSerial.Checked)
                {
                    normal_serial = 1;
                }
                else
                {
                    normal_serial = 0;
                }

                if (this.macSerial.Checked)
                {
                    mac_serial = 1;
                }
                else
                {
                    mac_serial = 0;
                }

                comp_group = this.compGroup.Text.Trim();

                try
                {
                    myConnection.Open();
                    SqlCommand sql_cmd = myConnection.CreateCommand();
                    sql_cmd.CommandText = "UPDATE [231_Comp] SET [CompID] = '" + partno + "', [CompName] = '" + compname + "',"
                        + " [Product] = '" + product + "', [DCompName] = '" + partname + "', [AssemblyTime] = " + ass_time + ","
                        + " [InspectorTime] = " + ins_time + ", [WiringTime] = " + w_time + ", [WCheckTime] = " + wcheck_time + ","
                        + " [Serial] = '" + serial_prefix + "', [Type] = '" + comp_type + "', [CompGroup] = '" + comp_group + "',"
                        + " [NormalSerial] = " + normal_serial + ", [MACSerial] = " + mac_serial
                        + " WHERE [CompID] = '" + this.compid + "'";
                    sql_cmd.ExecuteNonQuery();
                    sql_cmd.Dispose();
                    myConnection.Close();
                    MessageBox.Show("Update Comp successfully.");
                    this.Dispose();
                }
                catch
                {
                    MessageBox.Show("Cannnot update Comp.");
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                }                
            }
            else
            {
                MessageBox.Show(err);
            }
        }    
    }
}
